package org.geeks.config;

import java.io.File;
import java.util.UUID;

import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.expression.common.LiteralExpression;
import org.springframework.integration.annotation.Gateway;
import org.springframework.integration.annotation.MessagingGateway;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.file.FileNameGenerator;
import org.springframework.integration.file.remote.session.CachingSessionFactory;
import org.springframework.integration.file.remote.session.SessionFactory;
import org.springframework.integration.ftp.outbound.FtpMessageHandler;
import org.springframework.integration.ftp.session.DefaultFtpSessionFactory;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;

/**
 * CacheConfig
 * 
 * @author Geek4J
 *
 */
@Configuration
public class FTPConfig {

	@Value("${ftp.host}")
	private String host;

	@Value("${ftp.port}")
	private Integer port;

	@Value("${ftp.username}")
	private String username;

	@Value("${ftp.password}")
	private String password;

	/**
	 * Define SessionFactory
	 * 
	 * @return SessionFactory
	 */
	@Bean
	public SessionFactory<FTPFile> ftpSessionFactory() {
		DefaultFtpSessionFactory sf = new DefaultFtpSessionFactory();
		sf.setHost(host);
		sf.setPort(port);
		sf.setUsername(username);
		sf.setPassword(password);
		return new CachingSessionFactory<FTPFile>(sf);
	}

	@Bean
	@ServiceActivator(inputChannel = "ftpChannel")
	public MessageHandler handler() {
		FtpMessageHandler handler = new FtpMessageHandler(ftpSessionFactory());
		handler.setRemoteDirectoryExpression(new LiteralExpression("/"));
		handler.setFileNameGenerator(new FileNameGenerator() {

			@Override
			public String generateFileName(Message<?> message) {
				return UUID.randomUUID().toString();
			}

		});
		return handler;
	}

	@MessagingGateway
	public interface FTPGateway {

		@Gateway(requestChannel = "ftpChannel")
		void sendToFtp(File file);

		@Gateway(requestChannel = "ftpChannel")
		void sendToFtp(byte[] bytes);

	}

}